const remoteVideo = document.getElementById('remoteVideo');
const filePathInput = document.getElementById('filePath');
const playBtn = document.getElementById('playBtn');
const pauseBtn = document.getElementById('pauseBtn');
const startBtn = document.getElementById('startBtn');
const statusDiv = document.getElementById('status');

let connection;
let myPeerConnection;
let trackMonitorInterval;
let statsInterval;  // RTP 统计定时器

// 更新状态显示
function updateStatus(msg) {
    statusDiv.textContent = '状态: ' + msg;
    console.log('状态: ' + msg);
}

// WebSocket 连接
function connect() {
    connection = new WebSocket('ws://localhost:8080/player');
    connection.onmessage = handleSignalingMessage;
    connection.onopen = () => {
        updateStatus('已连接 WebSocket');
        console.log('WebSocket 已连接');
    };
    connection.onclose = () => updateStatus('WebSocket 断开');
    connection.onerror = (e) => {
        updateStatus('WebSocket 错误: ' + e);
        console.error('WebSocket 错误', e);
    };
}

// 发送消息
function sendToServer(msg) {
    if (connection && connection.readyState === WebSocket.OPEN) {
        console.log('Sending to server:', msg);
        connection.send(JSON.stringify(msg));
    } else {
        console.error('WebSocket 未打开');
        updateStatus('发送失败: 未连接');
    }
}

// 创建 PeerConnection：配置为本地 RTP（纯接收）
function createPeerConnection() {
    myPeerConnection = new RTCPeerConnection({
        iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
        iceTransportPolicy: 'all'
    });

    myPeerConnection.onicecandidate = (event) => {
        if (event.candidate) {
            sendToServer({
                id: 'onIceCandidate',
                candidate: event.candidate
            });
        }
    };

    myPeerConnection.ontrack = (event) => {
        remoteVideo.srcObject = event.streams[0];
        updateStatus('接收 RTP 流，开始播放');
        console.log('ontrack 触发，流已绑定');
        console.log('Track details:', event.track.kind, 'ID:', event.track.id, 'Stream ID:', event.streams[0].id);
        // 新增：监听轨道静音事件
          event.track.onmuted = () => {
            console.log('Track muted:', event.track.kind);
            if (event.track.kind === 'video') {
              updateStatus('警告：视频轨道无流，已静音'); // 提示用户
            }
          };

        // 轨道事件监听
        event.track.onended = () => console.log('Track ended:', event.track.kind);
        event.track.onmute = () => console.log('Track muted:', event.track.kind);
        event.track.onunmute = () => console.log('Track unmuted:', event.track.kind);
        event.track.onstarted = () => console.log('Track started:', event.track.kind);  // 新增
        event.track.readyState = 'live';  // 尝试设置，但浏览器控制
    };

    myPeerConnection.onconnectionstatechange = () => {
        const state = myPeerConnection.connectionState;
        updateStatus('连接状态: ' + state);
        console.log('Connection state changed to:', state);
    };

    myPeerConnection.oniceconnectionstatechange = () => {
        console.log('ICE connection state:', myPeerConnection.iceConnectionState);
    };

    myPeerConnection.ondtlsstatechange = () => {
        console.log('DTLS state:', myPeerConnection.dtlsState);
    };

    // 轨道状态监控
    trackMonitorInterval = setInterval(() => {
        if (myPeerConnection.getReceivers) {
            console.log('Track monitor:');
            myPeerConnection.getReceivers().forEach((receiver, index) => {
                if (receiver.track) {
                    console.log(`Receiver ${index}: kind=${receiver.track.kind}, readyState=${receiver.track.readyState}, muted=${receiver.track.muted}, ended=${receiver.track.ended}`);
                } else {
                    console.log(`Receiver ${index}: no track`);
                }
            });
        }
    }, 2000);

    // RTP 统计监控
    statsInterval = setInterval(() => {
        myPeerConnection.getStats().then(stats => {
            let totalBytes = 0;
            let totalLost = 0;
            stats.forEach(report => {
                if (report.type === 'inbound-rtp') {
                    console.log('RTP inbound stats:', report.kind, 'bytesReceived:', report.bytesReceived, 'packetsLost:', report.packetsLost, 'jitter:', report.jitter);
                    totalBytes += report.bytesReceived || 0;
                    totalLost += report.packetsLost || 0;
                }
            });
            console.log('Total RTP bytesReceived:', totalBytes, 'total packetsLost:', totalLost);
        }).catch(err => console.error('getStats failed:', err));
    }, 3000);
}

// 开始连接：创建 Offer（无本地媒体）
startBtn.onclick = async () => {
    if (myPeerConnection) return;
    createPeerConnection();

    updateStatus('PeerConnection 已创建（纯接收模式）');

    try {
        const offer = await myPeerConnection.createOffer({
            offerToReceiveAudio: true,
            offerToReceiveVideo: true
        });
        await myPeerConnection.setLocalDescription(offer);

        const mLines = myPeerConnection.localDescription.sdp.split('\n').filter(line => line.startsWith('m=')).join('\n');
        console.log('Offer SDP m-lines order:\n' + mLines);

        console.log('Full Offer SDP:', myPeerConnection.localDescription.sdp);

        sendToServer({
            id: 'start',
            sdpOffer: myPeerConnection.localDescription
        });
        updateStatus('Offer 已发送');
    } catch (err) {
        console.error('创建 Offer 失败: ' + err);
        updateStatus('Offer 创建失败');
    }
};

// 播放：读取路径，发送合并指令
playBtn.onclick = () => {
    const filePath = filePathInput.value.trim();
    if (!filePath) {
        alert('请输入文件路径');
        return;
    }
    const msg = {
        id: 'loadAndPlay',
        file: filePath
    };
    console.log('Play button clicked, sending loadAndPlay:', msg);
    sendToServer(msg);
    updateStatus('加载并播放请求已发送: ' + filePath);
};

// 暂停
pauseBtn.onclick = () => {
    const msg = { id: 'pause' };
    console.log('Pause button clicked, sending pause:', msg);
    sendToServer(msg);
    updateStatus('暂停指令已发送');
};

// 处理信令消息
function handleSignalingMessage(event) {
    const json = JSON.parse(event.data);
    console.log('Received from server:', json);
    switch (json.id) {
        case 'startResponse':
            console.log('Received startResponse, setting remote description');
            myPeerConnection.setRemoteDescription(new RTCSessionDescription({
                type: 'answer',
                sdp: json.sdpAnswer
            })).then(() => {
                console.log('Remote description set successfully');
                updateStatus('SDP 协商完成，等待 RTP');
            }).catch(err => {
                console.error('设置 Answer 失败: ' + err);
                updateStatus('SDP 协商失败');
            });
            break;
        case 'iceCandidate':
            console.log('Received iceCandidate, adding to peer');
            myPeerConnection.addIceCandidate(new RTCIceCandidate(json.candidate))
                .catch(err => console.error('添加 ICE 失败: ' + err));
            break;
        case 'playEnd':
            console.log('Received playEnd from server');
            updateStatus('播放结束');
            console.log('播放结束');
            clearInterval(trackMonitorInterval);
            clearInterval(statsInterval);
            break;
        case 'error':
            console.log('Received error from server:', json.message);
            updateStatus('错误: ' + json.message);
            console.error('服务器错误: ' + json.message);
            clearInterval(trackMonitorInterval);
            clearInterval(statsInterval);
            break;
    }
}

// 初始化
connect();
updateStatus('初始化中...');